<template>
  <div v-show="showLoading" class="page_loading" @touchstart="touchstart">
    <div class="loading_text" :style="{color:progressBarColor}">{{ loadingText }}</div>
    <div class="progress_bar">
      <div class="progress_bar_child" :style="{'width':`${progressBar}%`,'background':progressBarColor}"></div>
    </div>
    <div class="loading_error">加载失败，{{ second }}秒后返回上一页</div>
  </div>
</template>

<script>
export default {
  name: "pageLoading",
  data() {
    return {
      showLoading: true,
      loadingText: "LOADING...",
      progressBar: 0,
      second: 3,
      progressBarColor: "#ffdd00"
    }
  },
  created() {
    const THAT = this;
    let timer = setInterval(() => {
      if (THAT.progressBar >= 100) {
        clearInterval(timer);
        return;
      }
      let random = Math.random() * 5;
      if (THAT.progressBar + random <= 90) {
        THAT.progressBar += random;
      } else {
        THAT.progressBar = 90;
      }
    }, 50);
    setTimeout(() => {

      this.close()
    }, 5000)
  },
  methods: {
    touchstart(e) {
      e.preventDefault();
    },
    gotoBack() {
      this.second = 3;
      let timer = setInterval(() => {
        if (this.second == 0) {
          clearTimeout(timer);
          this.$router.go(-1);
          return;
        }
        this.second -= 1;
      }, 1000);
    },
    close(code) {
      this.progressBar = 100;
      if (code == 200) {
        this.progressBarColor = "#25e425";
        this.loadingText = "SUCCESS";
      } else {
        this.progressBarColor = "red";
        this.loadingText = "ERROR 404";
      }
      let timer = setTimeout(() => {
        clearTimeout(timer);
        if (code == 200) {
          this.showLoading = false;
        } else {
          // this.gotoBack();
        }
      }, 300)
    }
  }
}
</script>

<style lang="css" scoped>
@import "./pageLoading.css";
</style>